<template>
  <div class="app-container customer-div">
    <el-form :model="customerForm" size="mini" label-width="130px" :rules="rules" ref="customerForm" style="width:1000px">
          <div style="margin-top: 20px">
            <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
            <span class="font-small">客户信息</span>
          </div>
          <el-card shadow="never" style="margin-top:20px">
            <el-col :span="12">
              <el-form-item label="规模性质：" prop="newNature">
                <el-select v-model="customerForm.newNature" clearable @change="changenewNature">
                  <el-option v-for="(item,index) in newNatureList" :key="index" :value="item" :label="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 新增字段 -->
            <el-col :span="12">
              <el-form-item label="统一社会信用代码：" prop="businessCode">
                <el-input v-model.trim="customerForm.businessCode"  @blur="seachRepeat" clearable style="width:200px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称：" prop="customerName">
                <el-input v-model="customerForm.customerName" style="width:200px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户性质：">
                <el-select v-model="customerForm.customerQuality" @change="changeQuality">
                  <el-option v-for="item in customerQualityList"  :key="item.cddId"  :value="item.cddId" :label="item.cddValue" :disabled="customerForm.newNature == 'Z2(撮合)' && item.cddId == '108'"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户规模：" prop="newScale">
                <el-select v-model="customerForm.newScale" clearable>
                  <el-option v-for="(item,index) in newScaleList" :key="index" :value="item" :label="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

<!--            <el-col :span="12">-->
<!--              <el-form-item label="月用量(吨)：">-->
<!--                <el-input type="number" v-model="customerForm.aboutBuyNum" style="width:200px" clearable></el-input>-->
<!--              </el-form-item>-->
<!--            </el-col>-->

<!--            <el-col :span="12">-->
<!--              <el-form-item label="预估吨毛利(元)：">-->
<!--                <el-input type="number" v-model="customerForm.aboutPerProfit" style="width:200px" clearable></el-input>-->
<!--              </el-form-item>-->
<!--            </el-col>-->

            <el-col :span="12">
              <el-form-item label="客户协助人：">
                <el-select v-model="customerForm.subChargeIds" filterable placeholder="请选择" clearable multiple>
                  <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="客户分类：">
                <el-select v-model="customerForm.customerNewType" placeholder="请选择" clearable :disabled="customerForm.newNature == 'Z2(撮合)'">
                  <el-option
                    v-for="item in customerTypeList"
                    :key="item.cddValue"
                    :label="item.cddValue"
                    :value="item.cddValue">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="开票是否明细：">
                <el-radio-group v-model="customerForm.isInvoiceNeedDetail">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

          </el-card>

          <div style="margin-top: 20px">
            <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
            <span class="font-small">联系人信息<span style="color:Red">(必须填一条)</span></span>
          </div>
          <el-card shadow="never" style="margin-top:20px">
            <el-table :data="customerForm.customerContact" border style="width: 100%;margin:20px 0">
              <el-table-column
                align="center"
                label="联系人"
                width="150">
                <template slot-scope="scope">
                    <el-form-item :prop="`customerContact.${scope.$index}.contactName`" :rules="rules.contactName" label-width="0px">
                      <el-input v-model="scope.row.contactName" clearable style="width:100%" ></el-input>
                    </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="手机号"
                width="150"
                align="center">
                <template slot-scope="scope">
                  <el-form-item :prop="`customerContact.${scope.$index}.contactMobile`" :rules="rules.contactMobile" label-width="0px">
                    <el-input v-model="scope.row.contactMobile" clearable style="width:100%" @blur="seachRepeat2(scope.row.contactMobile,scope.$index)"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="职务"
                width="150"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px">
                    <el-select
                      v-model="scope.row.contactDuty"
                      placeholder="请选择/输入"
                      clearable
                      filterable
                      allow-create
                      default-first-option>
                      <el-option v-for="(item,index) in contactDutyList" :key="index" :label="item" :value="item"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column  label="是否为主联系人" width="150" align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px">
                      <el-radio-group v-model="scope.row.isMainContact">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                      </el-radio-group>
                  </el-form-item>

                </template>
              </el-table-column>
              <el-table-column  label="是否有采购决定权" width="150" align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px">
                    <el-radio-group v-model="scope.row.isBuyPermission">
                      <el-radio :label="1">是</el-radio>
                      <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="关注点"
                width="150"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px">
                    <el-input v-model="scope.row.contactFocus" clearable></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="生日"
                width="200"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px">
                    <el-date-picker
                      v-model="scope.row.contactBirthday"
                      type="date"
                      format="yyyy 年 MM 月 dd 日"
                      value-format="yyyy-MM-dd"
                      placeholder="选择日期"
                      style="width: 180px;">
                    </el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="爱好"
                width="150"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px">
                    <el-input v-model="scope.row.contactHobby" clearable></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column  label="操作" width="100" align="center" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" @click="delContact(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" size="small" @click="addContact">增加联系人</el-button>
          </el-card>

          <div style="margin-top: 20px">
            <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
            <span class="font-small">产品信息</span>
          </div>
          <el-card shadow="never" style="margin-top:20px">
            <el-table :data="customerForm.useGoods" border style="width: 100%;margin:20px 0">
              <el-table-column
                width="150"
                align="center"
                label="品类">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`useGoods.${scope.$index}.categoryId`" :rules="rules.categoryId">
                    <el-cascader
                      :filter-method="filterMethod"
                      :key="categoryIdKey"
                      filterable
                      :ref="'category'+scope.$index"
                      @change="changeCategoryId(scope.$index,scope.row)"
                      :options="categoryList" clearable v-model="scope.row.categoryId" :props="{emitPath:false,value:'categoryId',label:'categoryName'}"></el-cascader>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                width="200"
                align="center"
                label="牌号">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`useGoods.${scope.$index}.goodsSnId`" :rules="rules.goodsSnId">
                    <el-select
                      multiple
                      v-model="scope.row.goodsSnId"
                      filterable
                      placeholder="请选择/输入厂家牌号"
                      clearable>
                      <el-option
                        v-for="(item,index) in goodsList[scope.$index]"
                        :key="index"
                        :label="item.brandName+'/'+item.goodsSn"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="月使用量"
                width="150"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`useGoods.${scope.$index}.monthUseNum`" :rules="rules.monthUseNum">
                    <el-input type="number" v-model="scope.row.monthUseNum" clearable></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                width="200"
                align="center"
                label="替换牌号">
                <template slot-scope="scope">
                  <el-form-item label-width="0px">
                    <el-select
                      v-model="scope.row.replaceGoodsSnId"
                      filterable
                      multiple
                      placeholder="请选择/输入厂家牌号"
                      clearable>
                      <el-option
                        v-for="(item,index) in goodsList[scope.$index]"
                        :key="index"
                        :label="item.brandName+'/'+item.goodsSn"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column  label="采购渠道" width="150" align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`useGoods.${scope.$index}.supplierName`" :rules="rules.supplierName">
                    <el-select v-model="scope.row.supplierName" clearable multiple>
                      <el-option label="聚合厂" value="聚合厂"></el-option>
                      <el-option label="贸易商" value="贸易商"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                min-width="260"
                align="center"
                label="竞对名称">
                <template slot-scope="scope">
                    <el-tag
                      style="margin-bottom:5px;margin-right:5px"
                      size="small"
                      v-for="(tag,index) in scope.row.competitor"
                      :key="tag"
                      closable
                      @close="delCompetitor(scope.$index,index)">
                      {{tag}}
                    </el-tag>
<!--                    <el-tag v-if="scope.row.competitor.length ==0" size="small" style="margin-bottom:5px;margin-right:5px">后续确认</el-tag>-->
                    <el-button  class="button-new-tag" size="mini" @click="addCompetitor(scope.$index)">+ 添加</el-button>
                </template>
              </el-table-column>


              <el-table-column  label="操作" width="100" align="center" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" @click="delUseGoods(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" size="small" @click="addUseGoods">增加产品信息</el-button>
          </el-card>

          <!-- 新增字段 -->
          <div style="margin-top: 20px">
            <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
            <span class="font-small">生产经营</span>
          </div>
          <el-card shadow="never" style="margin-top:20px">
            <el-row>
                <el-col :span="8">
                  <el-form-item label="所属行业：">
                     <el-select
                       @change="changeNewIndustry"
                      v-model="customerForm.newIndustry"
                      placeholder="请选择/输入"
                      clearable
                      filterable
                      allow-create
                      default-first-option>
                      <el-option v-for="(item,index) in newIndustryList" :key="index" :label="item" :value="item"></el-option>
                      <el-option label="贸易" value="贸易" v-if="customerForm.customerQuality == 108"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="主营产品：">
                    <el-input v-model="customerForm.mainProduct" clearable style="width: 300px;"></el-input>
                  </el-form-item>
                </el-col>
            </el-row>
            <el-table :data="customerForm.customerDownstream" border style="width: 100%;margin:10px 0 20px">
              <el-table-column
                width="250"
                align="center"
                label="下游客户">
                <template slot-scope="scope">
                  <el-form-item label-width="0px">
                    <el-input v-model="scope.row.downstreamName" clearable></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="需求产品"
                width="250"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px">
                    <el-input v-model="scope.row.product" clearable></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column  label="客户级别" width="150" align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px">
                    <el-select v-model="scope.row.level" clearable>
                      <el-option v-for="(item,index) in levelList" :key="index" :label="item" :value="item"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column  label="订单情况" width="200" align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px">
                    <el-input v-model="scope.row.orderRemark" clearable></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column  label="操作" width="100" align="center" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" @click="delDownstream(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" size="small" @click="addDownstream">增加下游客户</el-button>

              <el-form-item label="回款情况：" style="margin-top:20px">
                <div class="flexTableStyle">
                  <el-select v-model="customerForm.returned" style="width: 150px;" clearable>
                    <el-option v-for="(item,index) in returnedList" :key="index" :label="item" :value="item"></el-option>
                  </el-select>
                  <el-form-item v-if="customerForm.returned=='账期'" prop="returnedDay" label="账期天数" label-width="80px">
                    <el-input-number
                      v-model="customerForm.returnedDay"
                      :min="1"
                      :controls="false"
                      :precision="0"
                      ></el-input-number>
                      <span>天</span>
                  </el-form-item>
                </div>
              </el-form-item>
              <el-form-item label="结算方式：" style="margin-top:20px">
                 <el-checkbox-group v-model="customerForm.settlement" style="display:flex;flex-direction:column;font-size:12px;">
                    <el-row>
                      <el-col :span="2">
                        <el-checkbox label="账期">账期</el-checkbox>
                      </el-col>
                      <el-col :span="22" v-if="customerForm.settlement.indexOf('账期')!=-1">
                        <div class="flexTableStyle">
                          <el-form-item label="利率(%):" label-width="80px" prop="interestRate">
                            <el-input-number
                              v-model="customerForm.interestRate"
                              :min="0"
                              :controls="false"
                              :precision="2"
                            ></el-input-number>
                          </el-form-item>
                          <el-form-item label="到期时间:" label-width="80px" prop="accountingPeriod">
                            <el-input-number
                              v-model="customerForm.accountingPeriod"
                              :min="1"
                              :controls="false"
                              :precision="0"
                              ></el-input-number>
                              <span>天</span>
                          </el-form-item>
                        </div>
                      </el-col>
                    </el-row>
                    <el-row style="margin-top:10px;margin-bottom:10px;">
                      <el-col :span="2">
                        <el-checkbox label="现金">现金</el-checkbox>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="2">
                        <el-checkbox label="承兑">承兑</el-checkbox>
                      </el-col>
                      <el-col :span="22" v-if="customerForm.settlement.indexOf('承兑')!=-1">
                        <el-form-item label="贴息点数:" label-width="80px" prop="subsidyInterest">
                          <el-input-number
                            v-model="customerForm.subsidyInterest"
                            :min="0"
                            :controls="false"
                            :precision="2"
                          ></el-input-number>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-checkbox-group>
              </el-form-item>
          </el-card>

          <div style="margin-top: 20px">
            <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
            <span class="font-small">公司信息</span>
          </div>
          <el-card shadow="never" style="margin-top:20px">
              <el-row>
                  <el-col :span="8">
                      <el-form-item label="法人：" prop="legalPerson">
                        <el-input v-model="customerForm.legalPerson"></el-input>
                      </el-form-item>
                  </el-col>

                  <el-col :span="16">
                    <el-form-item label="成立日期：" prop="issueDate">
                      <el-date-picker
                        value-format="yyyy-MM-dd"
                        v-model="customerForm.issueDate"
                        type="date"
                        placeholder="选择日期">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
              </el-row>
                <el-form-item label="所在地区：" v-model="diQuIds" prop="diQuIds">
                  <el-cascader
                    @change="chooseAreaId"
                    v-model="diQuIds"
                    ref="diQuIds"
                    :props="{ value: 'areaId',label:'areaName',children:'areaChildList' }"
                    :options="options">
                  </el-cascader>
                </el-form-item>

                <el-form-item label="详细地址：" prop="regAddress">
                  <el-input v-model="customerForm.regAddress"></el-input>
                </el-form-item>
                <el-form-item label="经营范围：" prop="businessInfo">
                  <el-input v-model="customerForm.businessInfo" :autosize="{ minRows: 2, maxRows: 6}" type="textarea" :rows="2" ></el-input>
                </el-form-item>
          </el-card>
      </el-form>
      <div style="margin-top:20px;text-align: center;width:1000px">
          <el-button size="small" @click="toBalck">返回</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading" size="small">确定</el-button>
      </div>

    <el-dialog
      title="添加竞对"
      :visible.sync="dialogVisible2"
      width="360px">
      <el-input v-model.trim="businessCode" @blur="seachRepeatCompanyName" clearable  placeholder="请输入竞对信用码"></el-input>
      <div style="font-weight: bold;font-size: 14px;padding-top: 20px;">自动匹配抬头：{{companyName}}</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="sumbitname">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getCustomerSetting,
  getAddressList,
  checkBusinessCode,
  checkContactMobile,
  getCompanyInfo,
  getOrderUsersList,
  orderGoodsList,
  getConfigList,
} from '@/api/partner';
import {
  getCustomerInfoAPI,
  addCustomerAPI,//新增客户
  getBrandAndGoodsSn,
  getCategoryList
} from '@/api/company';
import { formatDate } from '@/utils/date';
import { validatePhone } from '@/utils/validate';
import store from '@/store';
import { mapGetters } from 'vuex';
const defaultCustomerForm = {
  businessCode:'',//社会统一信用码
  customerName: '',//客户名称
  customerQuality:'',//客户性质
  newScale:'',//客户规模
  newNature:'',//规模性质
  aboutBuyNum:'',//月使用量
  aboutPerProfit: '',//吨毛利
  subChargeIds:[],//客户协助人
  //newLevel: '',//客户级别
  customerContact: [],//联系人列表
  useGoods: [],//产品信息列表
  customerDownstream: [],//生产经营
  newIndustry: '',//客户行业
  mainProduct: '',//主营产品
  returned:'',//回款方式
  returnedDay: '',//账期天数
  settlement: [],//结算方式
  interestRate:'',//利率
  accountingPeriod:'',//账期
  subsidyInterest: '',//贴息点
  legalPerson: '',//法人
  issueDate: '',//成立日期
  areaInfo:'',//省市区文字
  provinceId:'',//所属省ID
  cityId:'',//所属市ID
  areaId: '',//所属区ID
  regAddress:'',//企业地址
  businessInfo:'',//经营范围
  customerNewType:'',//客户分类
  isInvoiceNeedDetail:1
};
const defeaultContactItem = {//新增联系人
  contactId: '',//编辑ID
  contactName:'',//联系人
  contactMobile: '',//手机号
  contactDuty:'',//职务
  isMainContact:'',//是否主联系人
  isBuyPermission:'',//是否有采购决定权
  contactFocus:'',//关注的内容
  contactBirthday:'',//生日日期
  contactHobby:'',//爱好
};
const defeaultGoodLineItem = {//新增产品信息
  ugId:'',//id（编辑用）
  categoryId:'',//产品线id
  goodsSn:'',//牌号
  monthUseNum:'',//月使用量
  supplierName:[],//采购渠道
  goodsSnId:[],
  categoryName:'',
  replaceGoodsSnId:[],
  competitor:[]
};
const defaultDownstream = {//新增生产经营
  downstreamId:'',//id(编辑用)
  downstreamName:'',//客户名字
  product:'',//客户产品
  level: '',//客户级别
  orderRemark:'',//订单情况
};

export default {
  name: "index",
  data() {
    const isvalidatePhone = (rule, value, callback) => {
      if (!validatePhone(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    };
    const isdiQuIds = (rule, value, callback) => {
      if (!this.diQuIds.length) {
        callback(new Error('请选择所在地区'))
      } else {
        callback()
      }
    };
    return {
      newScaleList:[],//客户规模
      newNatureList:[],//规模性质
      newLevelList:[],//客户信息客户级别
      purchaseLevelList:[],//采购量级
      newIndustryList:[],//所属行业
      returnedList:[],//回款情况
      contactDutyList:[],//职务
      supplierNameList:[],//采购渠道
      levelList: [],//生产经营客户级别
      userOptionList: [],
      goodsList:[],//牌号
      customerForm: JSON.parse(JSON.stringify(defaultCustomerForm)),
      goodsLineList: [],
      btnLoading: false,
      options: [],
      diQuIds: [],
      customerQualityList: [],
      roles: store.getters.roles ? store.getters.roles : [],
      numOptions:[],

      categoryList:[],
      customerTypeList:[],
      categoryIdKey:1,

      companyName:'',
      businessCode:'',
      dialogVisible2:false,
      cutIndex:''
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    monthTotal:function() {
      if (this.customerForm.useGoods.length) {
        const totalList=this.customerForm.useGoods.map((res) => {
          console.log(res.cycleNumber)
          return +res.cycleNumber
        })
        const total = totalList.reduce((acc, curr) => acc + curr, 0);
        return total.toFixed(3)
      } else {
        return 0
      }
    },
    rules:function () {
      return {
        businessCode: [{ required: this.customerForm.newNature != 'Z2(撮合)', message: '请输入社会统一信用码', trigger: 'blur' },],
        customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
        newNature:[{ required: true, message: '请选择规模性质', trigger: 'change' }],
        contactName: [{ required: true, message: '请输入主联系人', trigger: 'blur' }],
        contactMobile: [{
          required: true,
          validator: (rule, value, callback) => {
            if (!validatePhone(value)) {
              callback(new Error('请输入正确的手机号'))
            } else {
              callback()
            }
          },
          trigger: 'blur' },],
        legalPerson: [{ required: this.customerForm.newNature != 'Z2(撮合)', message: '请输入公司法人', trigger: 'blur' }],
        issueDate: [{ required: this.customerForm.newNature != 'Z2(撮合)', message: '请选择成立日期', trigger: 'change' }],
        returnedDay: [
          { required: true, message: '请输入账期天数', trigger: 'blur' },
        ],
        interestRate: [
          { required: true, message: '请输入利率', trigger: 'blur' },
        ],
        accountingPeriod:[
          { required: true, message: '请输入到期时间', trigger: 'blur' },
        ],
        subsidyInterest: [
          { required: true, message: '请输入贴息点数', trigger: 'blur' },
        ],
        categoryId:[{required: true, trigger: 'change' ,message: '此项必填',}],
        goodsSnId:[{required: true, trigger: 'change' ,message: '此项必填',}],
        monthUseNum:[{required: true, trigger: 'blur' ,message: '此项必填',}],
        supplierName:[{required: this.customerForm.newNature != 'Z2(撮合)' && this.customerForm.newNature != 'Z(撮合)', trigger: 'change' ,message: '此项必填',}],
        competitor:[{required: true,
          validator: (rule, value, callback) => {
            let indexArray = rule.field.split(".");
            let i = indexArray[1];
            if (this.customerForm.useGoods[i].supplierName == '竞争对手' && !value) {
              callback(new Error('请输入竞对名称'))
            }else{
              callback()
            }
          },
          trigger: 'change' }],
      }

    },
  },
  created() {
    this.getCustomerInfo();
    this.getCustomerSettingList();
    this.getAddressListData();
    this.getUserOptionListData();
    this.getCustomerType()
    this.numOptions = []
    for(let i=0;i<1000;i=i+100){
       let label = i == 0 ? (i+1)+'-'+(i+99) : i+'-'+(i+99)
       this.numOptions.push({value:i+99,label: label,children: []});
    }
    this.numOptions.push({value:100,label: '1000吨以上'})
    this.numOptions.forEach((el,index)=>{
      if(el.children){
        let max = el.value;
        let min = el.value-99 <= 0  ? 1 : el.value-99
        this.numOptions[index].children = []
        for(let ii=min; ii<=max;ii++){
          this.numOptions[index].children.push({value:ii,label: ii})
        }
      }
    })
    this.getcategoryListFn()

  },
  filters: {
    formatCreateTime(time) {
      if (time) {
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      } else {
        return '--'
      }
    },
  },
  components: {
  },
  methods: {
    filterMethod(node, keyword){
      let text = node.text.toLowerCase();
      let val = keyword.toLowerCase();
      return text.includes(val)
    },
    sumbitname(){
      if(this.companyName == ''){
        this.$message.error('抬头没有匹配！')
        return false
      }
      this.customerForm.useGoods[this.cutIndex].competitor.push(this.companyName)
      this.dialogVisible2 = false
    },
    seachRepeatCompanyName() {
      getCompanyInfo({businessCode:this.businessCode}).then((companyInfo) => {
        this.companyName = companyInfo.companyName;
        if(companyInfo.companyName == ''){
          this.businessCode = '';
        }
      }).catch(() => {
        this.businessCode = '';
      })
    },
    delCompetitor(i,ii){
      this.customerForm.useGoods[i].competitor.splice(ii,1)
    },
    addCompetitor(i){
      this.cutIndex = i
      this.businessCode = ''
      this.companyName = ''
      this.dialogVisible2 = true
    },
    changenewNature(){
      this.customerForm.customerNewType = ''
      this.customerForm.customerQuality = ''
    },
    //获取订单分类列表
    getCustomerType(){
      getConfigList({status:1}).then((res)=>{
        let customerType = res.find((el)=>{
          return  el.cdtCode == 'customer_new_type'
        })
        this.customerTypeList = customerType ? customerType.data : []
      })
    },
    changeGoodsSn(index,e){
        console.log(index,e)
      let i = this.goodsList[index].findIndex((el)=>{
        return el.id == e
      })
      if(i!= -1){
        this.customerForm.useGoods[index].goodsSn = this.goodsList[index][i]['goodsSn']
        this.customerForm.useGoods[index].brandId = this.goodsList[index][i]['brandId']
        this.customerForm.useGoods[index].brandName = this.goodsList[index][i]['brandName']
        this.customerForm.useGoods[index].sapGoodsNo = this.goodsList[index][i]['sapGoodsNo']
      }else{
        this.customerForm.useGoods[index].goodsSn = ''
        this.customerForm.useGoods[index].brandId = ''
        this.customerForm.useGoods[index].brandName = ''
        this.customerForm.useGoods[index].sapGoodsNo = ''
      }
      console.log(this.customerForm)
    },
    //获取品类列表
    getcategoryListFn(){
      getCategoryList().then((res)=>{
        this.categoryList = res.list
      })
    },
    //切换品类
    changeCategoryId(index, row){
      let chooseList = this.customerForm.useGoods.filter((el)=>{
        return this.customerForm.useGoods[index].categoryId == el.categoryId
      })
      if(chooseList.length > 1){
        let c = JSON.parse(JSON.stringify(this.customerForm.useGoods[index]))
        c.categoryId = ''
        c.categoryName = ''
        c.goodsSnId = [];
        c.replaceGoodsSnId = []
        this.customerForm.useGoods.splice(index,1,c)
        this.$nextTick(()=>{
          this.categoryIdKey = this.categoryIdKey+1
        })
        this.$message({
          type: "error",
          message: "品类已存在!",
        });
        return
      }
      this.customerForm.useGoods[index].categoryId = row.categoryId;
      this.$nextTick(()=>{
        this.customerForm.useGoods[index].categoryName = this.$refs['category'+index].getCheckedNodes()[0] ? this.$refs['category'+index].getCheckedNodes()[0]['label'] : ''
      })
      this.customerForm.useGoods[index].goodsSnId = [];
      this.customerForm.useGoods[index].replaceGoodsSnId = []
      this.getOrderGoodsList(row,index);
    },
    // 切换产品线
    changeGoodsId(index, row) {
      this.customerForm.useGoods[index].goodsLineId = row.goodsLineId;
      this.getOrderGoodsList(index,row);
    },
    // 获取牌号列表
    getOrderGoodsList(row,index){
      if(row.categoryId){
        getBrandAndGoodsSn({
          categoryId:row.categoryId
        }).then((res)=>{
          this.goodsList.splice(index,1,res.list)
          // this.goodsList = res.list
        })
      }
    },
    changeNewIndustry(){
      if(this.customerForm.newIndustry == '贸易'){
          this.customerForm.mainProduct = '贸易'
      }else{
          this.customerForm.mainProduct = ''
      }
    },
    changeQuality(){
      this.customerForm.newIndustry = '';
      this.customerForm.mainProduct = ''
    },
     //获取员工下拉选项
    getUserOptionListData(){
      getOrderUsersList({
        status:1
      }).then((res)=>{
        this.userOptionList = res;
      })
    },
    // 选择地区
    chooseAreaId(value) {
      this.customerForm.areaInfo = value.length ? this.$refs["diQuIds"].getCheckedNodes()[0].pathLabels.join("") : "";
      this.customerForm.provinceId = this.diQuIds[0] ? this.diQuIds[0] : null;
      this.customerForm.cityId = this.diQuIds[1] ? this.diQuIds[1] : null;
      this.customerForm.areaId = this.diQuIds[2] ? this.diQuIds[2] : null;
    },
    // 获取客户信息配置
    getCustomerInfo() {
      getCustomerInfoAPI({tab:1}).then((res) => {
        this.newScaleList=res;
      })
      getCustomerInfoAPI({tab:2}).then((res) => {
        this.newNatureList=res;
      })
      getCustomerInfoAPI({tab:3}).then((res) => {
        this.newLevelList=res;
      })
      getCustomerInfoAPI({tab:4}).then((res) => {
        this.purchaseLevelList=res;
      })
      getCustomerInfoAPI({tab:5}).then((res) => {
        this.newIndustryList=res;
      })
      getCustomerInfoAPI({tab:6}).then((res) => {
        this.returnedList=res;
      })
      getCustomerInfoAPI({tab:7}).then((res) => {
        this.contactDutyList=res;
      })
      getCustomerInfoAPI({tab:8}).then((res) => {
        this.supplierNameList=res;
      })
      getCustomerInfoAPI({tab:9}).then((res) => {
        this.levelList=res;
      })
    },

    //删除联系人
    delContact(index) {
      this.customerForm.customerContact.splice(index, 1)
    },
    //新增联系人
    addContact() {
      this.customerForm.customerContact.push(JSON.parse(JSON.stringify(defeaultContactItem)))
    },
    //删除产品信息
    delUseGoods(index) {
      this.customerForm.useGoods.splice(index, 1)
    },
    //新增产品信息
    addUseGoods() {
      this.customerForm.useGoods.push(JSON.parse(JSON.stringify(defeaultGoodLineItem)))
    },
    //删除生产经营
    delDownstream(index) {
      this.customerForm.customerDownstream.splice(index, 1)
    },
    //新增生产经营
    addDownstream() {
      this.customerForm.customerDownstream.push(JSON.parse(JSON.stringify(defaultDownstream)))
    },
     //获取省市区列表
    getAddressListData() {
      getAddressList().then((res) => {
        this.options = res;
      })
    },

    //返回
    toBalck() {
      this.$router.go(-1)
    },

    //查询客户是否存在
    seachRepeat() {
      if (this.customerForm.businessCode) {
        checkBusinessCode({
          businessCode: this.customerForm.businessCode,
          customerId: this.customerForm.customerId ? this.customerForm.customerId : 0
        }).then((res) => {
          getCompanyInfo({
            businessCode: this.customerForm.businessCode
          }).then((companyInfo) => {
            this.customerForm.businessCode = companyInfo.businessCode;
            this.customerForm.customerName = companyInfo.companyName;
            this.customerForm.businessInfo = companyInfo.businessInfo;
            this.customerForm.issueDate = companyInfo.issueDate;
            this.customerForm.legalPerson = companyInfo.legalPerson;
            this.customerForm.provinceId = companyInfo.provinceId;
            this.customerForm.cityId = companyInfo.cityId;
            this.customerForm.areaId = companyInfo.areaId;
            this.customerForm.areaInfo = companyInfo.areaNames;
            this.customerForm.regAddress = companyInfo.regAddress;
            this.diQuIds = [this.customerForm.provinceId, this.customerForm.cityId, this.customerForm.areaId];
          }).catch(()=>{
            this.customerForm.businessCode = '';
          })
        }).catch((rej) => {
          if (rej.code == 10001) {
            this.$alert(rej.msg, '提示', {
              confirmButtonText: '确定',
            });
            this.customerForm.businessCode = '';
          }
        })
      }
    },

    //查询手机号是否存在
    seachRepeat2(contactMobile, index) {
      if (contactMobile != '') {
        checkContactMobile({
          contactMobile:contactMobile,
          customerId: this.customerForm.customerId ? this.customerForm.customerId : 0,
          newNature:this.customerForm.newNature
        }).then((res) => {
        }).catch((rej) => {
          if (rej.code == 10000 || rej.code == 10001) {
            this.$message.error(rej.msg);
            let c = JSON.parse(JSON.stringify(this.customerForm.customerContact[index]));
            c.contactMobile = '';
            this.customerForm.customerContact.splice(index,1,c)
          }
        })
      }
    },

    //提交新建编辑
    handleConfirm() {
      if (this.customerForm.customerContact.length == 0) {
        this.$message.error('请添加联系人');
        return false
      }
      let data=JSON.parse(JSON.stringify(this.customerForm))
      data.subChargeIds = this.customerForm.subChargeIds.join(',')
      if (data.customerContact[0].contactMobile == '12345678910') {//无定性客户
        if (data.businessCode == '' && data.newNature != 'Z2(撮合)') {
          this.$message.error('请添加统一社会信用代码');
          return false
        } else if (data.customerName == '' ) {
          this.$message.error('请输入客户名称');
          return false
        } else {
          this.btnLoading = true;
          addCustomerAPI(data).then(() => {
            this.btnLoading = false;
            this.toBalck()
          }).catch(() => {
            this.btnLoading = false;
          })
        }
      } else {
        this.$refs.customerForm.validate((valid) => {//普通客户
          if (valid) {
            this.btnLoading = true;
            addCustomerAPI(data).then(() => {
              this.btnLoading = false;
              this.toBalck()
            }).catch(() => {
              this.btnLoading = false;
            })
          } else {
            this.$message.error('请检查必填项');
          }
        })
      }
    },

    //获取客户配置
    getCustomerSettingList() {
      getCustomerSetting().then((res) => {
        res.forEach((el) => {
          if (el.cdtCode == 'customer_state') {
            this.customerStateList = el.data
          }
          else if (el.cdtCode == 'customer_quality') {//客户性质
            this.customerQualityList = el.data;
          }
          else if (el.cdtCode == 'goods_line') {//产品线
            this.goodsLineList = el.data
          }
        });
      })
    },
  },
};
</script>

<style scoped lang="scss">
.flexTableStyle{
  display: flex;
}
</style>
